package com.example.lib_audio.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.example.lib_audio.R

class ProgressPlayView(context: Context,attrs:AttributeSet?):View(context,attrs) {
    private var mRadius = 0f
    private var currentProgress = 0f
    private val startAngle = 270f
    private val mPaint:Paint by lazy{
        Paint().apply {
            isAntiAlias = true
            style = Paint.Style.STROKE
            strokeWidth = dp2px(2)
        }
    }
    private val playBitmap:Bitmap by lazy {
        BitmapFactory.decodeResource(resources, R.drawable.bottom_stop)
    }

    private val stopBitmap:Bitmap by lazy {
        BitmapFactory.decodeResource(resources, R.drawable.bottom_play)
    }

    private var currentBitmap = stopBitmap

    private val mBitmapRect:RectF by lazy {
        val center = width/2f
        RectF(center-mRadius/2f,(height/2f-mRadius/2f),center+mRadius/2f,height-mRadius/2f)
    }

    private val arcRect:RectF by lazy {
        RectF(dp2px(2),dp2px(2),width-dp2px(2),height-dp2px(2))
    }


    init {
        setOnClickListener {
            changeBitmap()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),MeasureSpec.getSize(heightMeasureSpec))
    }


    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mRadius = width/2f
    }


    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        if(canvas != null){
            //绘制背景圆环
            mPaint.color = Color.parseColor("#64646E")
            canvas.drawCircle(width/2f,height/2f,mRadius- dp2px(2),mPaint)

            //绘制进度
            mPaint.color = Color.WHITE
            canvas.drawArc(arcRect,startAngle,currentProgress,false,mPaint)

            //绘制暂停和播放图片
            canvas.drawBitmap(currentBitmap,null,mBitmapRect,null)
        }

    }


    fun changeBitmap(){
        currentBitmap = if(currentBitmap == playBitmap){
            stopBitmap
        }else{
            playBitmap
        }
        invalidate()
    }

    fun changeProgress(progress:Float){
        currentProgress = progress * 360
        invalidate()
    }

    fun dp2px(dp:Int) = resources.displayMetrics.density*dp
}